package com.qf.shop.filesystem.controller;

import com.qf.shop.common.core.utils.R;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private Auth auth;

    @Value("${qiniu.bucket}")
    private String bucket;


    @Value("${qiniu.host}")
    private String host;

    @PostMapping("/upload")
    public R fileUpload(MultipartFile file) {
        // 1.获取token
        String token = auth.uploadToken(bucket);
        try {
            // 2.上传
            Response response = uploadManager.put(file.getBytes(), file.getOriginalFilename(), token);
            return R.ok().put("data", host + file.getOriginalFilename());
        } catch (IOException e) {
            log.error("上传文件失败", e);
            return R.error("文件上传失败");
        }
    }

}
